package vip.liux.contracts.infrastructure.messaging.handlers;

import lombok.Setter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessagingException;
import org.springframework.web.client.RestClient;
import vip.liux.contracts.infrastructure.messaging.MessageConst;
import vip.liux.contracts.shared.enums.messing.ChannelType;

import java.io.Serializable;
import java.net.URI;

public class WebHookMessageHandler extends AbstractMessageHandler {

    @Setter
    private RestClient restClient = RestClient.builder().build();

    public WebHookMessageHandler() {
    }

    public WebHookMessageHandler(RestClient restClient) {
        this.restClient = restClient;
    }

    @Override
    public void handleMessage(Message<?> message) throws MessagingException {
        // 从消息头中提取 WebHook URL
        String webhookUrl = (String) message.getHeaders().get(MessageConst.TO);
        if (webhookUrl == null || webhookUrl.isEmpty()) {
            throw new MessagingException("Missing 'webhookUrl' header in the message");
        }

        // 获取消息内容
        Object payload = message.getPayload();
        if (!(payload instanceof Serializable)) {
            throw new MessagingException("Unsupported payload type: " + payload.getClass());
        }

        try {
            // 使用 RestClient 发送 POST 请求
            ResponseEntity<String> response = restClient.post()
                    .uri(URI.create(webhookUrl))
                    .header(HttpHeaders.CONTENT_TYPE, "application/json")
                    .body(payload)
                    .retrieve()
                    .toEntity(String.class);

            // 检查响应状态码
            if (!response.getStatusCode().is2xxSuccessful()) {
                throw new MessagingException("Failed to send webhook, response code: " + response.getStatusCode());
            }
        } catch (Exception e) {
            throw new MessagingException("Error occurred while sending webhook to " + webhookUrl, e);
        }
    }

    @Override
    public boolean supports(ChannelType channelType) {
        return ChannelType.WEBHOOKS.equals(channelType);
    }
}